// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.entity.FundsPayOrder;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.FundsPayOrderInfoMapper;
import com.fowo.api.mapper.FundsPayOrderMapper;
import com.fowo.api.mapper.PaymentRecordMapper;
import com.fowo.api.model.funds.pay.order.FundsPayOrderExcelPo;
import com.fowo.api.model.funds.pay.order.FundsPayOrderInvalidateAction;
import com.fowo.api.model.funds.pay.order.FundsPayOrderItemVo;
import com.fowo.api.model.funds.pay.order.FundsPayOrderSearchParamPo;
import com.fowo.api.model.funds.pay.order.FundsPayOrderVo;
import com.fowo.api.model.funds.pay.order.info.FundsPayOrderInfoSearchParamPo;
import com.fowo.api.model.payment.record.PaymentRecordSearchParamPo;
import com.fowo.api.service.FundsPayOrderInfoService;
import com.fowo.api.service.FundsPayOrderService;
import com.fowo.api.service.PaymentRecordService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 请款单 服务实现类
 * @author 蜂窝蜜造平台 配置人：鹿丙涛，沈友谅
 */
@Service
@Slf4j
@DataObjectType(FundsPayOrder.class)
@DS("ds24")
public class FundsPayOrderServiceImpl
  extends ServiceImpl<FundsPayOrderMapper, FundsPayOrder>
  implements FundsPayOrderService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("applicantName", "su.`name`");
      put("paymentUserName", "su2.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected FundsPayOrderService self;

  @Resource
  protected FundsPayOrderInfoService fundsPayOrderInfoService;

  @Resource
  protected PaymentRecordService paymentRecordService;

  @Resource
  protected SysSerialService sysSerialService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected FundsPayOrderInvalidateAction fundsPayOrderInvalidateAction;

  @Resource
  protected Validator validator;

  /**
   * 创建请款单
   * @param model 请款单
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(FundsPayOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    FundsPayOrder entity = new FundsPayOrder();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getStatus() == null) {
      entity.setStatus("QK00");
    }

    if (model.getExchangeRateType() == null) {
      entity.setExchangeRateType("2");
    }
    // 填充序列号
    if (!StringUtils.hasText(entity.getOrderId())) {
      entity.setOrderId(
        sysSerialService.getNewSerial(
          new NewSerialRequest(null, "FundsPayOrder.orderId")
        )
      );
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("请款单保存失败");
  }

  /**
   * 更新所有子表
   * @param model 请款单
   */
  protected void updateAllChilds(FundsPayOrderVo model) throws Exception {
    if (model.getInfoList() != null) {
      fundsPayOrderInfoService.saveAllByParentId(
        model.getId(),
        model.getInfoList()
      );
    }

    if (model.getRecordList() != null) {
      paymentRecordService.saveAllByParentId(
        model.getId(),
        model.getRecordList()
      );
    }
  }

  /**
   * 更新请款单
   * @param model 请款单
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(FundsPayOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    FundsPayOrder entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("请款单不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser",
      "recordList",
      "convertInto"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      return true;
    }
    return false;
  }/**
   * 更新请款单（带空值）
   * @param model 请款单
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(FundsPayOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    FundsPayOrder entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("请款单不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(FundsPayOrder::getLastUpdateTime, model.getLastUpdateTime())
      .set(FundsPayOrder::getLastUpdateUser, model.getLastUpdateUser())
      .set(FundsPayOrder::getPayerTypeName, model.getPayerTypeName())
      .set(FundsPayOrder::getDescribe, model.getDescribe())
      .set(FundsPayOrder::getBudgetRatio, model.getBudgetRatio())
      .set(FundsPayOrder::getPredictFkTime, model.getPredictFkTime())
      .set(FundsPayOrder::getUserName, model.getUserName())
      .set(FundsPayOrder::getBankOfDeposit, model.getBankOfDeposit())
      .set(FundsPayOrder::getBankAccount, model.getBankAccount())
      .set(FundsPayOrder::getPayCurrency, model.getPayCurrency())
      .set(FundsPayOrder::getExchangeRateType, model.getExchangeRateType())
      .set(FundsPayOrder::getExchangeRate, model.getExchangeRate())
      .set(FundsPayOrder::getWithdrawDimension, model.getWithdrawDimension())
      .set(FundsPayOrder::getRemark, model.getRemark())
      .set(
        model.getAttachment() != null,
        FundsPayOrder::getAttachment,
        JSON.toJSONString(model.getAttachment())
      )
      .setSql(model.getAttachment() == null, "attachment = null")
      .eq(FundsPayOrder::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(FundsPayOrderSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 请款信息(infoList) 对应的对象
    FundsPayOrderInfoSearchParamPo infoListSearchParam =
      new FundsPayOrderInfoSearchParamPo();
    infoListSearchParam.setDisableDataPremissions(true);
    infoListSearchParam.setParentIdInList(ids);
    FundsPayOrderInfoMapper localFundsPayOrderInfoMapper = ContextHolder
      .getApplicationContext()
      .getBean(FundsPayOrderInfoMapper.class);
    infoListSearchParam.applySqlSegments();
    List<Long> infoListIdList = localFundsPayOrderInfoMapper.searchIds(
      infoListSearchParam
    );
    if (!infoListIdList.isEmpty()) {
      FundsPayOrderInfoService localFundsPayOrderInfoService = ContextHolder
        .getApplicationContext()
        .getBean(FundsPayOrderInfoService.class);
      localFundsPayOrderInfoService.batchDelete(infoListIdList);
    }

    // 处理子表字段 付款记录(recordList) 对应的对象
    PaymentRecordSearchParamPo recordListSearchParam =
      new PaymentRecordSearchParamPo();
    recordListSearchParam.setDisableDataPremissions(true);
    recordListSearchParam.setParentIdInList(ids);
    PaymentRecordMapper localPaymentRecordMapper = ContextHolder
      .getApplicationContext()
      .getBean(PaymentRecordMapper.class);
    recordListSearchParam.applySqlSegments();
    List<Long> recordListIdList = localPaymentRecordMapper.searchIds(
      recordListSearchParam
    );
    if (!recordListIdList.isEmpty()) {
      PaymentRecordService localPaymentRecordService = ContextHolder
        .getApplicationContext()
        .getBean(PaymentRecordService.class);
      localPaymentRecordService.batchDelete(recordListIdList);
    }
  }

  /**
   * 删除请款单
   * @param id 请款单的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除请款单
   * @param ids 请款单的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    FundsPayOrderSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "status",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00083")
      );
      exportOptions.addFieldMappingOption(
        "costType",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00084")
      );
      exportOptions.addFieldMappingOption(
        "payerType",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00085")
      );
      exportOptions.addFieldMappingOption(
        "settlementType",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00004")
      );
      exportOptions.addFieldMappingOption(
        "payType",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00005")
      );
      exportOptions.addFieldMappingOption(
        "predictFkTime",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addFieldMappingOption(
        "applicant",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((FundsPayOrderItemVo) r).getApplicantName())
          )
      );
      exportOptions.addFieldMappingOption(
        "paymentUser",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((FundsPayOrderItemVo) r).getPaymentUserName())
          )
      );
      exportOptions.addStringFields(
        "orderId",
        "associatedOrder",
        "payer",
        "status",
        "costType",
        "payerType",
        "payerTypeName",
        "settlementType",
        "exchangeType",
        "payType",
        "applicantName",
        "applyRemark",
        "paymentUserName",
        "paymentRemark"
      );

      String fileName = String.format(
        "请款单(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> statusItems = sysDictService.getDictItems("SCM00083");
    List<SysDictAllItem> costTypeItems = sysDictService.getDictItems(
      "SCM00084"
    );
    List<SysDictAllItem> payerTypeItems = sysDictService.getDictItems(
      "SCM00085"
    );
    List<SysDictAllItem> settlementTypeItems = sysDictService.getDictItems(
      "SCM00004"
    );
    List<SysDictAllItem> payTypeItems = sysDictService.getDictItems("SCM00005");
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<FundsPayOrderExcelPo> items = new ArrayList<FundsPayOrderExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<FundsPayOrderItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<FundsPayOrderItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (FundsPayOrderItemVo item : list) {
        FundsPayOrderExcelPo excel = new FundsPayOrderExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getStatus() != null) {
          statusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getStatus()))
            .findFirst()
            .ifPresent(i -> excel.setStatus(i.getItemText()));
        }
        if (item.getCostType() != null) {
          costTypeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getCostType()))
            .findFirst()
            .ifPresent(i -> excel.setCostType(i.getItemText()));
        }
        if (item.getPayerType() != null) {
          payerTypeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getPayerType()))
            .findFirst()
            .ifPresent(i -> excel.setPayerType(i.getItemText()));
        }
        if (item.getSettlementType() != null) {
          settlementTypeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getSettlementType()))
            .findFirst()
            .ifPresent(i -> excel.setSettlementType(i.getItemText()));
        }
        if (item.getPayType() != null) {
          payTypeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getPayType()))
            .findFirst()
            .ifPresent(i -> excel.setPayType(i.getItemText()));
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "请款单(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(FundsPayOrderExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过关联单号查询请款单主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByAssociatedOrder(String associatedOrder) {
    return this.baseMapper.getIdByAssociatedOrder(associatedOrder);
  }

  /**
   * 通过关联单号查询请款单多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByAssociatedOrder(List<String> list) {
    return this.baseMapper.getIdsByAssociatedOrder(list);
  }

  /**
   * 通过请款单主键查询关联单号
   */
  @Override
  public String getAssociatedOrderById(Long id) {
    return this.baseMapper.getAssociatedOrderById(id);
  }

  /**
   * 通过请款单主键查询关联单号列表
   */
  @Override
  public List<String> getAssociatedOrderByIds(List<Long> ids) {
    List<Map<String, Object>> maps =
      this.baseMapper.getAssociatedOrderByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap ->
            (String) stringObjectMap.get("associatedOrder")
          )
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 请款单的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public FundsPayOrderVo getVoById(Long id) throws Exception {
    FundsPayOrderVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    FundsPayOrderInfoSearchParamPo infoListSearchParamPo =
      new FundsPayOrderInfoSearchParamPo();
    infoListSearchParamPo.setParentId(id);
    infoListSearchParamPo.getExtendData().put("queryMode", "sub");
    infoListSearchParamPo.getExtendData().put("queryParent", "FundsPayOrder");
    infoListSearchParamPo.applySqlSegments();
    vo.setInfoList(fundsPayOrderInfoService.search(infoListSearchParamPo));

    PaymentRecordSearchParamPo recordListSearchParamPo =
      new PaymentRecordSearchParamPo();
    recordListSearchParamPo.setParentId(id);
    recordListSearchParamPo.getExtendData().put("queryMode", "sub");
    recordListSearchParamPo.getExtendData().put("queryParent", "FundsPayOrder");
    recordListSearchParamPo.applySqlSegments();
    vo.setRecordList(paymentRecordService.search(recordListSearchParamPo));

    return vo;
  }

  /**
   * 分页查询请款单
   * @param search 查询条件
   * @return 请款单分页查询结果
   */
  @Override
  public Page<FundsPayOrderItemVo> pageSearch(
    FundsPayOrderSearchParamPo search
  ) {
    Page<FundsPayOrderItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(FundsPayOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 请款单快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'FundsPayOrderOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<FundsPayOrderItemVo>> searchOptions(
    FundsPayOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询请款单
   * @param search 查询条件
   * @return 请款单列表查询结果
   */
  @Override
  public List<FundsPayOrderItemVo> search(FundsPayOrderSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询请款单最后更新时间
   * @param search 查询条件
   * @return 请款单最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(FundsPayOrderSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 作废
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了作废操作"
  )
  @Override
  public void invalidate(Long id) throws Exception {
    if (fundsPayOrderInvalidateAction == null) {
      throw new Exception("此操作当前不可用");
    }
    fundsPayOrderInvalidateAction.run(id);
  }

  /**
   * 全部
   */
  @Override
  public List<FundsPayOrderItemVo> allType(FundsPayOrderSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.allType(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<FundsPayOrderItemVo> allTypePage(
    FundsPayOrderSearchParamPo search
  ) {
    Page<FundsPayOrderItemVo> allTypePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return allTypePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return allTypePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    allTypePage =
      this.baseMapper.allTypePage(
          search.toPage(this.baseMapper.allTypeCount(search)),
          search
        );
    List<Long> recordIds = allTypePage
      .getRecords()
      .stream()
      .map(FundsPayOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return allTypePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return allTypePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    allTypePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return allTypePage;
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date allTypeLastUpdateTime(FundsPayOrderSearchParamPo search) {
    return this.baseMapper.allTypeLastUpdateTime(search);
  }

  /**
   * 待审批
   */
  @Override
  public List<FundsPayOrderItemVo> approval(FundsPayOrderSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.approval(search);
  }

  /**
   * 待审批分页
   */
  @Override
  public Page<FundsPayOrderItemVo> approvalPage(
    FundsPayOrderSearchParamPo search
  ) {
    Page<FundsPayOrderItemVo> approvalPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return approvalPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return approvalPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    approvalPage =
      this.baseMapper.approvalPage(
          search.toPage(this.baseMapper.approvalCount(search)),
          search
        );
    List<Long> recordIds = approvalPage
      .getRecords()
      .stream()
      .map(FundsPayOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return approvalPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return approvalPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    approvalPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return approvalPage;
  }

  /**
   * 查询待审批最后更新时间
   * @param search 查询条件
   * @return 待审批最后更新时间
   */
  @Override
  public Date approvalLastUpdateTime(FundsPayOrderSearchParamPo search) {
    return this.baseMapper.approvalLastUpdateTime(search);
  }

  /**
   * 待付款
   */
  @Override
  public List<FundsPayOrderItemVo> obligation(
    FundsPayOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.obligation(search);
  }

  /**
   * 待付款分页
   */
  @Override
  public Page<FundsPayOrderItemVo> obligationPage(
    FundsPayOrderSearchParamPo search
  ) {
    Page<FundsPayOrderItemVo> obligationPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return obligationPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return obligationPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    obligationPage =
      this.baseMapper.obligationPage(
          search.toPage(this.baseMapper.obligationCount(search)),
          search
        );
    List<Long> recordIds = obligationPage
      .getRecords()
      .stream()
      .map(FundsPayOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return obligationPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return obligationPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    obligationPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return obligationPage;
  }

  /**
   * 查询待付款最后更新时间
   * @param search 查询条件
   * @return 待付款最后更新时间
   */
  @Override
  public Date obligationLastUpdateTime(FundsPayOrderSearchParamPo search) {
    return this.baseMapper.obligationLastUpdateTime(search);
  }

  /**
   * 已完成
   */
  @Override
  public List<FundsPayOrderItemVo> completed(
    FundsPayOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.completed(search);
  }

  /**
   * 已完成分页
   */
  @Override
  public Page<FundsPayOrderItemVo> completedPage(
    FundsPayOrderSearchParamPo search
  ) {
    Page<FundsPayOrderItemVo> completedPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return completedPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return completedPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    completedPage =
      this.baseMapper.completedPage(
          search.toPage(this.baseMapper.completedCount(search)),
          search
        );
    List<Long> recordIds = completedPage
      .getRecords()
      .stream()
      .map(FundsPayOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return completedPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return completedPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    completedPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return completedPage;
  }

  /**
   * 查询已完成最后更新时间
   * @param search 查询条件
   * @return 已完成最后更新时间
   */
  @Override
  public Date completedLastUpdateTime(FundsPayOrderSearchParamPo search) {
    return this.baseMapper.completedLastUpdateTime(search);
  }

  /**
   * 已驳回
   */
  @Override
  public List<FundsPayOrderItemVo> reject(FundsPayOrderSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.reject(search);
  }

  /**
   * 已驳回分页
   */
  @Override
  public Page<FundsPayOrderItemVo> rejectPage(
    FundsPayOrderSearchParamPo search
  ) {
    Page<FundsPayOrderItemVo> rejectPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return rejectPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return rejectPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    rejectPage =
      this.baseMapper.rejectPage(
          search.toPage(this.baseMapper.rejectCount(search)),
          search
        );
    List<Long> recordIds = rejectPage
      .getRecords()
      .stream()
      .map(FundsPayOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return rejectPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return rejectPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    rejectPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return rejectPage;
  }

  /**
   * 查询已驳回最后更新时间
   * @param search 查询条件
   * @return 已驳回最后更新时间
   */
  @Override
  public Date rejectLastUpdateTime(FundsPayOrderSearchParamPo search) {
    return this.baseMapper.rejectLastUpdateTime(search);
  }

  /**
   * 已作废
   */
  @Override
  public List<FundsPayOrderItemVo> cancellation(
    FundsPayOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.cancellation(search);
  }

  /**
   * 已作废分页
   */
  @Override
  public Page<FundsPayOrderItemVo> cancellationPage(
    FundsPayOrderSearchParamPo search
  ) {
    Page<FundsPayOrderItemVo> cancellationPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return cancellationPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return cancellationPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    cancellationPage =
      this.baseMapper.cancellationPage(
          search.toPage(this.baseMapper.cancellationCount(search)),
          search
        );
    List<Long> recordIds = cancellationPage
      .getRecords()
      .stream()
      .map(FundsPayOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return cancellationPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return cancellationPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    cancellationPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return cancellationPage;
  }

  /**
   * 查询已作废最后更新时间
   * @param search 查询条件
   * @return 已作废最后更新时间
   */
  @Override
  public Date cancellationLastUpdateTime(FundsPayOrderSearchParamPo search) {
    return this.baseMapper.cancellationLastUpdateTime(search);
  }
}
